package com.atguigu.system.service.impl;

import com.atguigu.common.helper.MenuHelper;
import com.atguigu.common.helper.RouterHelper;
import com.atguigu.model.system.SysMenu;
import com.atguigu.model.system.SysUser;
import com.atguigu.model.vo.RouterVo;
import com.atguigu.model.vo.SysUserQueryVo;
import com.atguigu.system.mapper.SysMenuMapper;
import com.atguigu.system.mapper.SysUserMapper;
import com.atguigu.system.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysMenuMapper sysMenuMapper;


    @Override
    public void updateStatus(Long id, Integer status) {
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setStatus(status);
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public IPage<SysUser> selectPage(Page<SysUser> pageParam, SysUserQueryVo userQueryVo) {
        return sysUserMapper.selectPage(pageParam, userQueryVo);
    }

    @Override
    public SysUser getSysUserByUsername(String username) {
        SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("username", username));
        return sysUser;

    }

    @Override
    public Map<String, Object> getInfo(Long userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);

        //根据当前用户id查询菜单表数据
        //菜单和按钮权限，要区分超级管理员（直接查询所有）和普通管理（关联表查询）两种查询方式。
        List<SysMenu> userMenusList = getUserMenusByUserId(sysUser.getId());

        //构建树结构
        List<SysMenu> sysMenuTreeList = MenuHelper.buildTree(userMenusList);
        //根据菜单树构建路由树
        List<RouterVo> routers = RouterHelper.buildRouters(sysMenuTreeList); //菜单权限

        List<String> buttons = getUserBtnPermsByUserId(sysUser.getId()); //按钮权限,type=2

        Map<String, Object> map = new HashMap<>();
        map.put("name",sysUser.getName());
        map.put("avatar",sysUser.getHeadUrl());
        map.put("buttons", buttons);
        map.put("routers", routers);
        return map;
    }

    public List<SysMenu> getUserMenusByUserId(Long userId) {
        List<SysMenu> sysMenuList = null;
        if(userId == 1L){ // 系统上线时初始化的用户。
            //1.超级管理员 - 查所有
            sysMenuList  = sysMenuMapper.selectList(
                    new QueryWrapper<SysMenu>().eq("status",1)
                            .orderByAsc("sort_value"));
        }else{
            //2.普通管理员 - 进行关联查询
            //连表查询   sys_user -> sys_user_role -> sys_role -> sys_role_menu -> sys_menu
            // 有可能拥有重复权限，记得去重
            sysMenuList  = sysMenuMapper.getUserMenusByUserId(userId);
        }
        return sysMenuList;
    }

    public List<String> getUserBtnPermsByUserId(Long userId) {
        List<String> btnPermsList = new ArrayList<>();
        List<SysMenu> sysMenuList = getUserMenusByUserId(userId);
        if (!CollectionUtils.isEmpty(sysMenuList)){
            for (SysMenu sysMenu : sysMenuList) {
                if (sysMenu.getType() == 2){
                    btnPermsList.add(sysMenu.getPerms());

                }
            }
        }
        return btnPermsList;

    }
}
